<?php

namespace App\Http\Controllers\Pc;

use App\Lib\Utilities;
use App\Models\UserStore;
use Illuminate\Http\Request;

use App\Models\User;
use App\Models\Store;

use App\Http\Controllers\Controller;

//登录控制器

class LoginController extends Controller
{
    //登录页面
    public function index(){

        return view('pc.login')->with('title','后台登录');
    }

    //验证登录
    public function login(Request $request){
        $data = $request->input('str');

        $login_phone =  $request->input('username');
        $password = $request->input('password');
        $code = $request->input('code');
        //TODO::密码混淆
        $key = '&i*w|R0db-/+Z.}!l@_IkcCj(q%1yn3U]fhML$[O';
        $password = md5 (sha1($password) . $key);

        //验证手机验证码
        if(!Utilities::checkSmsCode($login_phone,2,$code)){
            return [
                'status' => 0,
                'message' => '验证码错误'
            ];
        }
        if($login_phone===null){
            return [
                'status' => 0,
                'message' => '请填写登录账号'
            ];
        }

        if($password===null){
            return [
                'status' => 0,
                'message' => '请填写密码'
            ];
        }
        $user = User::where('mobile',$login_phone)->where('password',$password)->first();

        if(!$user){
            return [
                'status' => 0,
                'message' => '用户名或密码错误'
            ];
        }else{
            //判断有没有店铺
            $user_store = UserStore::where('uid',$user->id)->where('rid',1)->first();
            if($user_store){
                session(['user_id' => $user->id  ]);
                return [
                    'status' => 1,
                    'message' => '登录成功！',
                    'data' => [
                        'store_id' => encrypt($user_store->sid)
                    ]
                ];
            }else{
                return [
                    'status' => 0,
                    'message' => '请使用店主账号登录'
                ];
            }

        }
        


    }

    //退出登录

    public function logout(Request $request){
        $request->session()->forget('user_id');
        return redirect("/pc/index/a");
    }

    public function agreement()
    {
        return view('pc.agreement');
    }
}
